import { createSlice } from '@reduxjs/toolkit'
import storage from '@/libs/storage'

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: storage.get('user') || {},
    token: storage.get('token') || ''
  },
  reducers: {
    setUser: (state, action) => {
      state.user = {
        ...state.user,
        ...action.payload
      }
    },
    setToken: (state, action) => {
      state.token = action.payload
    },
    logout: (state) => {
      state.user = {}
      state.token = ''
      storage.remove('token')
      storage.remove('user')
    }
  }
})

export const { setUser, setToken, logout } = userSlice.actions
export default userSlice.reducer